const app = getApp()
import { getProjectMemberList, inviteProjectMember, deleteProjectMember } from '../../../../api/index'

Page({
  data: {
    safeBottom: 0,
    projectId: '',
    list: [],
    keyword: '',
    showMemberPop: false
  },
  search ({ detail }) {
    this.setData({ keyword: detail })
    this.getList()
  },
  addMember () {
    this.setData({ showMemberPop: true })
  },
  closeMemberPop () {
    this.setData({ showMemberPop: false })
  },
  async deleteMember ({ currentTarget: { dataset: { item, index } } }) {
    try {
      const { confirm } = await wx.$pro.showModal({ title: '提示', content: '确定要删除该成员吗？',  })
      if (confirm) {
        await deleteProjectMember({ projectId: this.data.projectId, memberUserId: item.userId })
        wx.showToast({ title: '删除成功！', icon: 'none' })
        this.setData({ showHandles: false })
        this.data.list.splice(index, 1)
        this.setData({ list: this.data.list })
      }
    } catch (err) {
      wx.showToast({ title: err.message || err.ResultSet.errors, icon: 'none' })
    }
  },
  async confirmMember ({ detail }) {
    try {
      let ids = []
      detail.forEach(item => {
        ids.push(item.userId)
      })
      await inviteProjectMember({ projectId: this.data.projectId, userIdList: ids })
      wx.showToast({ title: '邀请成功！', icon: 'none' })
      this.getList()
    } catch (err) {
      wx.showToast({ title: err.message || err.ResultSet.errors, icon: 'none' })
    }
  },
  async getList () {
    try {
      let query = {
        projectId: this.data.projectId
      }
      if (this.data.keyword) query.searchName = this.data.keyword
      const { ResultSet } = await getProjectMemberList({ ...query })
      this.setData({
        list: ResultSet.userData.data,
      })
    } catch (err) {
      wx.showToast({ title: err.message || err.ResultSet.errors, icon: 'none' })
    }
  },
  onLoad ({ id }) {
    const { screenHeight, safeArea: { bottom } } = wx.$pro.getSystemInfoSync()
    this.setData({ safeBottom: screenHeight - bottom, projectId: id })
    this.getList()
  }
})